<?php

namespace App\Console\Commands;

use App\Models\CountryModel;
use App\Models\lazada\BigBagModel;
use App\Models\lazada\OrderModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class Test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $bigbags = BigBagModel::select([DB::raw('count(*) as count'), 'bigBagID', DB::raw('MIN(id) as id')])->groupBy('bigBagID')->get();

        foreach ($bigbags as $bigbag){
            if($bigbag->count > 1){
                echo "大包：" . $bigbag->bigBagID . "，有 {$bigbag->count}条\n";
                BigBagModel::where('bigBagID', $bigbag->bigBagID)->where('id', '<>', $bigbag->id)->delete();
            }
        }


        return Command::SUCCESS;
    }

    public function delete_order()
    {
        $bigbags = BigBagModel::where('parcelQty', '>', 1)->get();

        foreach ($bigbags as $bigbag){
            $orders = OrderModel::where('bigBagID', $bigbag->bigBagID)->count();

            if($orders > $bigbag->parcelQty){
                $order_ids = OrderModel::groupBy('orderCode')->select(DB::raw('MIN(id) as id'))->pluck('id');

                OrderModel::where('bigBagID', $bigbag->bigBagID)->whereNotIn('id', $order_ids)->delete();
            }
        }
    }


    public function test()
    {
        $bigbags = BigBagModel::where('parcelQty', '>', 1)->get();

        foreach ($bigbags as $bigbag){
            $parcelList = json_decode($bigbag->parcelList, true);

            $orderCode = [];
            foreach ($parcelList as $parcel){
                $orderCode[] = $parcel['orderCode'];
            }

            $updatedCount = OrderModel::whereIn('orderCode', $orderCode)->update([
                'bigBagID' => $bigbag->bigBagID
            ]);

            echo "大包：" . $bigbag->bigBagID . "，有 {$bigbag->parcelQty}条 更新了 {$updatedCount} 条订单记录\n";
        }
    }
}
